<template>
  <div class="main-wrapper">
    <div class="flex-container">
      <div class="scene-left width-col-6">
        <p class="scene-left-title">指标标签库</p>
        <MyTree ref="myTreeRef" :treeData="metricTree" from="metric" @transferCheckedCategory="receiveCheckedCategory"/>
        <!-- 自定义组 -->
        <CustomGroup 
          :customGroups="customGroups" 
          :closeEditInput="closeEditInput"
          @handleCreateGroup="submitCreateGroup"
          @handleClickCustomGroup="clickCustomGroup"
          @handleEditCustomGroup="submitEditGroup"
          @handleDeleteCustomGroup="deleteCustomGroup"/>
      </div>
      <div class="case-right width-col-18">
         <!-- 工具栏 -->
         <div class="search-wrap">
          <div class="toolbar" style="padding-bottom: 0px;">        
          </div>
          <div class="operaution-btn-group">
            <div>
              <el-button
                  size="small"
                  type="primary"
                  :disabled="!selectedCount"
                  @click="_handleAddToGroup"
                >添加到组
              </el-button>
            </div>
          </div>
        </div>
          <MyTable 
            ref="metricTable"
            currentTable ="metricTable"
            :hasSelection="true"
            :tableData="lists" 
            :tableItem="columns"
            :total="total"
            @handlePageChange="handlePageChange"
            @selectionChange="handleSelectionChange"
            />
      </div>
    </div>
    <!--弹窗-->
    <!-- 删除弹窗 -->
    <DeleteDialog :visible="isVisibleDeleteModal" @closeDialog="closeDeleteDialog" @submitDelete="submitDelete" :content="deleteContentText"/>
    <AppendGroupDialog :showModal="isVisibleAppendGroupModal" :customGroups="customGroups" :selectNum="selectedCount" @closeDialog="_closeAppendDialog" @handleDialogSubmit="_submitAppend"/>
  </div>
</template>
<script>
import {mapState} from 'vuex'
import {fetchMetricCategory, fetchMetricList,fetchCustomGroupForMetric,createCustomMetricGroup,updateCustomMetricGroup,deleteCustomMetricGroup,appendMetricInGroup,fetchGroupMertic} from '@/api/metric';
import MyTree from '@/components/MyTree';
import MyTable from '@/components/MyTable';
import AppendGroupDialog from '@/components/AppendGroup'
import DeleteDialog from '@/components/DeleteDialog'
import CustomGroup from '@/components/CustomGroup'
import addToGroupMixin from '@/mixins/group/add_to_group'
const metricMixin = new addToGroupMixin('metric')
  export default {
    mixins: [metricMixin],
    components: {
      MyTree,
      MyTable,
      AppendGroupDialog,
      DeleteDialog,
      CustomGroup
    },
    data(){
      return {
        deleteContentText: '确认删除该自定义组吗？删除时会将组里的数据一起清除。',
        metricTree: [{
          label: '行车',
          value: 'driving',
          has_children: true,
          children:[]
        },
        {
          label: '泊车',
          value: 'parking',
          has_children: true,
          children:[]
        }],
        lists: [],
        columns:[
          {
            name: '指标名称',
            prop: 'metric_name',
            width: '300px'
          },
          {
            name: '类别',
            prop: 'category',
            width: '200px'
          },
          {
            name: '子类别',
            prop: 'sub_category',
            width: '200px'
          },
          {
            name: '描述',
            prop: 'des',
            width: ''
          },
        ],
        total: 0,
        pageIndex: 1,
        pageSize: 20,
        checkedOption: [],
        customGroups: [],
        selectedCount: 0,
        selectedMetrics: [],
        isVisibleAppendGroupModal: false,
        isVisibleDeleteModal: false,
        closeEditInput:false
      }    
    },
    computed:{
      ...mapState({
        checkedCustomGroup: state => state.scene.checkedCustomGroup
      })
    },
    created(){
      this.getCatogry();  
      this.getCustomGroup();
    },
    methods: {
      // 获取metric类别，组装数据
      getCatogry(){
        const sceneArr = ['driving', 'parking']
        sceneArr.map(sceneVal => {
          fetchMetricCategory({scene: sceneVal}).then(res => {
            if(res.category && res.category.length>0){
              let result = res.category
              let index = this.metricTree.findIndex(element => element.value === sceneVal)
              result.forEach(element => {
              this.metricTree[index].children.push({label: element, value:element})
              }) 
              this.checkedOption = ['driving'] 
              this.getMetricList()
            }
        })
        })
      },
      // 点击类别查询列表
      receiveCheckedCategory(data){
        // 将自定义组件选中 置空
        this.$store.dispatch('scene/updateCheckedCustomGroup', {})
        this.checkedOption = this.getTreeValue(data)
          this.getMetricList()
      },
      // 将节点数据过滤，保留value值 给到后端
      getTreeValue(arr){
        let resultArr = []
        if(arr.length > -1) {
          for(let i=arr.length-1; i>=0;i--){
            resultArr.push(arr[i].value)
          }
        }
        return resultArr
      },
      getMetricList(pageParams){
        // // 点击默认标签组 的获取 metric 
        if(!this.checkedCustomGroup.id){
          const params = pageParams || {
            scene: this.checkedOption[0],
            sub_category: this.checkedOption[1],
            page_num: this.pageIndex,
            page_size: this.pageSize
          } 
          fetchMetricList(params).then(res => {
            if(res && res.data){
              this.lists = res.data
              this.total = res.total
            }
          })
        }else {
          // 点击自定义组 的获取 metric 
          const groupParams = {
            page_num: this.pageIndex,
            page_size: this.pageSize,
            group_id: this.checkedCustomGroup.id
          }
          fetchGroupMertic(groupParams).then(res => {
            if(res && res.data){
              this.lists = res.data
              this.total = res.total
            }
          })
        }
       
      },
      // 切换pagesize 、切换页码
      handlePageChange(pageData) {
        const pageParams = {
          ...pageData,
          scene: this.checkedOption[0],
          sub_category: this.checkedOption[1],
        }
        this.getMetricList(pageParams)
      },
      // 选择
      handleSelectionChange(val) {
        this.selectedMetrics = val.map(item => {
          return item.id
        })
        this.selectedCount = this.selectedMetrics.length   
      },
      // 获取左侧的自定义组列表
      getCustomGroup(){
        fetchCustomGroupForMetric().then(res => {
          this.customGroups = res.data
        })
      },
      // 点击icon 去增加input
      handleCreateGroup(){
        this.isShowAddInput = true
        this.$nextTick(() => {
          this.$refs['addGroupInput'].focus()
        })
      },
      // 提交 创建组
      submitCreateGroup(data){
        createCustomMetricGroup(data).then(res => {
          this.$message.success('创建组成功')
          this.getCustomGroup()      
        })
      },
      clickCustomGroup(data){
        this.$store.dispatch('scene/updateCheckedCustomGroup', data)
        //告知右侧为 自定义组
        this.$refs.myTreeRef.$refs.treeRef.setCurrentKey(null);
        this.getMetricList()
      }, 
       // 提交 编辑的group
      submitEditGroup(params){
        updateCustomMetricGroup(params).then(res => {
          this.$message.success('修改自定义组成功')
          this.getCustomGroup()
          this.closeEditInput= true
          setTimeout(() => {
            this.closeEditInput= false
          }, 500);
        })
      },
      deleteCustomGroup(){
        this.isVisibleDeleteModal = true
      },
      closeDeleteDialog(){
        this.isVisibleDeleteModal = false
      },
      // 提交 删除group
      submitDelete(){
        let params = {
          delete_group: this.checkedCustomGroup.id
        }
        deleteCustomMetricGroup(params).then(res => {
          this.isVisibleDeleteModal = false
          this.$message.success('删除自定义组成功')
          this.getCustomGroup()
          this.$store.dispatch('scene/updateCheckedCustomGroup', {})
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
 @import '@/styles/vars.scss' ;
   .scene-left{
     border-right: 1px solid rgba(0, 0, 0, 0.12);
     height: calc(100vh - 40px - $header-height);
     overflow: auto;
    .scene-left-title{
      color: #293b5a;
      padding: 21.5px;
      font-size: 13px;
      font-family: Source Han Sans CN;
      font-weight: 600;
      border-bottom: 1px solid rgba(0, 0, 0, 0.12);
    }
   }
</style>